<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @addTask="addTaskFn" :list="list"></TodoHeader>
    <TodoMain :list="showList" @delTask="delTaskFn"></TodoMain>
    <TodoFooter
      @changeType="changeTypeFn"
      :getSel="getSel"
      @clearTask="clearTaskFn"
      :totolnum="totolnum"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("Todolist")) || [],
      getSel: "all", //声明一个变量，默认为all，表示全部完成，yes表示已经完成，no表示未完成，TodoFooter点击改变状态。用计算属性，因为依靠其他变量来获得
      num: "", // 计算属性统计剩余数量值
    };
  },
  computed: {
    showList() {
      if (this.getSel === "yes") {
        return this.list.filter((item) => item.isDone === true);
      } else if (this.getSel === "no") {
        return this.list.filter((item) => item.isDone === false);
      } else if (this.getSel === "all") {
        return this.list;
      }
    },
    totolnum() {
      return (this.num = this.showList.length);
    },
  },
  methods: {
    // 1增加函数
    addTaskFn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      });
    },
    //2 减少函数
    delTaskFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 3切换状态
    changeTypeFn(type) {
      this.getSel = type;
    },
    // 4 清除已完成函数
    clearTaskFn(Type) {
      this.list = this.list.filter((item) => item.isDone === false);
    },
  },
  //5 监听本地存储
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("Todolist", JSON.stringify(this.list));
      },
    },
  },
};
</script>
